﻿@{
    Layout = null;
    string stockInTypeListJson = System.Text.Json.JsonSerializer.Serialize(
        ViewBag.StockInTypeList ?? new List<Model.WmsDictData>(),
        new System.Text.Json.JsonSerializerOptions
        {
            ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles,
            Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
        }
    );
    string orderStatusListJson = System.Text.Json.JsonSerializer.Serialize(
        ViewBag.OrderStatusList ?? new List<Model.WmsDictData>(),
        new System.Text.Json.JsonSerializerOptions
        {
            ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles,
            Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
        }
    );
}

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8" />
    <title>进货订单</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <link rel="stylesheet" href="//unpkg.com/element-plus/dist/index.css" />
    <script src="//unpkg.com/element-plus"></script>
    <script src="https://unpkg.com/element-plus/dist/locale/zh-cn.min.js"></script>
    <style>
        #tableBlock {
            margin: 0 auto;
            width: 1700px;
            padding-bottom: 20px;
            box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
            background-color: #fff;
        }

            #tableBlock label {
                font-size: 24px;
            }

        .formTableInput, .formTableSelect {
            display: inline-block;
            width: 180px;
        }

        .buttonBlock {
            height: 40px;
            width: 100%;
            padding-top: 10px;
            padding-left: 20px;
        }

        .pagination-container {
            margin-top: 20px;
            display: flex;
            justify-content: flex-end;
        }

        .audit-textarea {
            margin-top: 15px;
            width: 100%;
        }

        .operate-btn {
            margin-right: 8px;
        }

        .btnAndTable {
            margin: 0 auto;
            margin-left: 50px;
        }
    </style>
</head>
<body>
    <div id="app" class="common-layout"
         data-stock-in-type-list="@stockInTypeListJson"
         data-order-status-list="@orderStatusListJson">
        <div id="tableBlock">
            <!-- 查询表单（不变） -->
            <form>
                <table width="1700px" height="80px">
                    <tbody>
                        <tr style="background-color: #fff;">
                            <td height="40px" width="280px">
                                &nbsp;&nbsp;&nbsp;&nbsp<span>入库单号</span>&nbsp;&nbsp;&nbsp;&nbsp;
                                <el-input type="text" v-model="orderNoInput" id="orderNoInput" class="formTableInput" placeholder="请输入"></el-input>
                            </td>
                            <td height="40px" width="280px">
                                <span>入库类型</span>&nbsp;&nbsp;&nbsp;&nbsp;
                                <el-select v-model="selectedInboundType" class="formTableSelect" placeholder="请选择入库类型">
                                    <el-option v-for="(type, index) in stockInTypeList" :key="index" :label="type.Name" :value="type.Code"></el-option>
                                </el-select>
                            </td>
                            <td height="40px" width="280px">
                                <span>单据状态</span>&nbsp;&nbsp;&nbsp;&nbsp;
                                <el-select v-model="selectedStatus" class="formTableSelect" placeholder="请选择单据状态">
                                    <el-option v-for="(status, index) in orderStatusList" :key="index" :label="status.Name" :value="status.Code"></el-option>
                                </el-select>
                            </td>
                            <td height="40px" width="280px">
                                <span>仓库名称</span>&nbsp;&nbsp;&nbsp;&nbsp;
                                <el-select v-model="selectedWarehouse" class="formTableSelect" placeholder="请选择仓库名称" :filterable="true">
                                    <el-option v-for="(warehouse, index) in warehouseList" :key="warehouse.wareHouseId" :label="warehouse.warehouseName" :value="warehouse.wareHouseId.toString()"></el-option>
                                </el-select>
                            </td>
                            <td height="40px" width="160px">
                                <el-button type="reset" v-on:click ="resetForm">重置</el-button>&nbsp;
                                <el-button type="primary" v-on:click="searchTable">查询</el-button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </form>

            <div class="btnAndTable">
                <div class="buttonBlock">
                    <el-button type="primary" v-on:click="addOrder">新增</el-button>&nbsp;
                    <el-button type="danger" v-on:click="deleteOrder">删除</el-button>&nbsp;
                    <el-button type="default" v-on:click="copyOrder">复制</el-button>&nbsp;
                    <el-button type="danger" v-on:click="openAuditModal">审核</el-button>&nbsp;
                    <el-button type="danger" v-on:click="cancleCheck">撤销</el-button>&nbsp;
                    <el-button type="default" v-on:click="exportTable">导出</el-button>&nbsp;
                    <el-button type="success" v-on:click="refrushTable">刷新</el-button>&nbsp;
                </div>

                <!-- 表格（不变，操作列已存在） -->
                <el-table :data="tableData" style="width: 1600px; margin-top: 10px"
                          v-on:selection-change="handleSelectionChange" ref="multipleTable" stripe
                          :loading="isLoading">
                    <el-table-column fixed type="selection" width="50"></el-table-column>
                    <el-table-column fixed label="入库单号" width="150">
                        <template #default="scope">
                            <span style="color: #10b981; cursor: pointer;" v-on:click="jumpToDetail(scope.row)">
                                {{ scope.row.stockOrderNo }}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column fixed prop="stockType" label="入库类型" width="100" :formatter="formatStockTypeColumn"></el-table-column>
                    <el-table-column fixed prop="orderStatus" label="单据状态" width="100" :formatter="formatOrderStatusColumn"></el-table-column>
                    <el-table-column fixed prop="stockDate" label="入库日期" width="150" :formatter="formatDate"></el-table-column>
                    <el-table-column prop="warehouseName" label="仓库名称" width="120"></el-table-column>
                    <el-table-column prop="upOrderNo" label="关联单号" width="150"></el-table-column>
                    <<el-table-column prop="allGoodsName"
                                      label="入库货品"
                                      width="120"
                                      :formatter="formatAllGoodsName">
                    </el-table-column>
                    <el-table-column prop="operatorBy" label="经办人" width="120"></el-table-column>
                    <el-table-column prop="allOrderQuantity" label="入库数量(吨)" width="120" :formatter="(row) => row.allOrderQuantity.toFixed(2)"></el-table-column>
                    <el-table-column prop="purchaseUnitPriceCount" label="入库金额(元)" width="120" :formatter="(row) => row.purchaseUnitPriceCount.toFixed(2)"></el-table-column>
                    <el-table-column prop="createBy" label="制单人" width="120"></el-table-column>
                    <el-table-column prop="createOrgName" label="所在部门" width="120"></el-table-column>
                    <el-table-column prop="createTime" label="制单时间" width="120" :formatter="formatDate"></el-table-column>
                    <el-table-column prop="auditorBy" label="审核人" width="120"></el-table-column>
                    <el-table-column prop="auditorTime" label="审核时间" width="120" :formatter="formatDate"></el-table-column>
                    <el-table-column fixed="right" label="操作" min-width="180">
                        <template #default="scope">
                            <el-button v-if="['草稿', '待审核'].includes(getStatusText(scope.row.orderStatus))"
                                       class="operate-btn" link type="primary" v-on:click="handleEdit(scope.row)">编辑</el-button>
                            <el-button v-if="['草稿', '待审核'].includes(getStatusText(scope.row.orderStatus))"
                                       class="operate-btn" link type="danger" v-on:click="deleteSingleOrder(scope.row)">删除</el-button>
                            <el-button v-if="getStatusText(scope.row.orderStatus) === '驳回'"
                                       class="operate-btn" link type="primary" v-on:click="handleEdit(scope.row)">编辑</el-button>
                            <el-button v-if="['驳回', '未入库'].includes(getStatusText(scope.row.orderStatus))"
                                       class="operate-btn" link type="warning" v-on:click="handleRejectCancel(scope.row)">撤销</el-button>
                            <span v-if="['部分入库', '已完成'].includes(getStatusText(scope.row.orderStatus))">-</span>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 分页（不变） -->
            <div class="pagination-container">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                               :page-sizes="[10, 20, 50, 100]" :total="total"
                               layout="total, sizes, prev, pager, next, jumper"
                               v-on:size-change="handleSizeChange" v-on:current-change="handleCurrentChange">
                </el-pagination>
            </div>
        </div>

        <!-- 审核模态框（不变，补充逻辑） -->
        <el-dialog title="订单审核" v-model="isAuditModalOpen" width="500px" :before-close="handleAuditModalClose">
            <div class="audit-content">
                <el-radio-group v-model="selectedAuditResult" required>
                    <el-radio label="pass">通过</el-radio>
                    <el-radio label="reject">驳回</el-radio>
                </el-radio-group>
                <el-input class="audit-textarea" type="textarea" v-model="auditOpinion"
                          placeholder="请输入审核意见（驳回时必填）" :rows="4" :maxlength="200" show-word-limit></el-input>
            </div>
            <template #footer>
                <el-button v-on:click="isAuditModalOpen = false">取消</el-button>
                <el-button type="primary" v-on:click="confirmAudit">确认审核</el-button>
            </template>
        </el-dialog>
    </div>

    <script>
        const { createApp, ref, onMounted } = Vue;
        const { ElMessageBox, ElMessage } = ElementPlus;
        const app = createApp({
            setup() {
                // -------------------------- 1. 基础数据与变量（原有代码保留） --------------------------
                const warehouseList = ref([]);
                const stockInTypeList = ref([]);
                const orderStatusList = ref([]);
                const selectedInboundType = ref('');
                const selectedStatus = ref('');
                const selectedWarehouse = ref('');
                const orderNoInput = ref('');
                const dateRange = ref([]);
                const tableData = ref([]);
                const allTableData = ref([]); // 存储全量数据（关键）
                const currentPage = ref(1);
                const pageSize = ref(10);
                const total = ref(0);
                const isLoading = ref(false);

                // 新增：审核/删除相关变量
                const selectedRows = ref([]); // 表格选中行
                const multipleTable = ref(null); // 表格实例
                const isAuditModalOpen = ref(false); // 审核模态框显隐
                const selectedAuditResult = ref(''); // 审核结果（pass/reject）
                const auditOpinion = ref(''); // 审核意见
                const canAuditRows = ref([]); // 可审核的行（仅待审核状态）

                //获取登录人Id
                const getCurrentUserId = () => {
                    // 1. 从 sessionStorage 读取存储的 user JSON 字符串
                    const userStr = sessionStorage.getItem('YH');
                    if (!userStr) {
                        ElMessage.warning('未检测到登录状态，请重新登录');
                        return '';
                    }

                    try {
                        // 2. 解析 JSON 字符串为对象
                        const userObj = JSON.parse(userStr);
                        // 3. 提取 usersId（兼容可能的空值）
                        const userId = userObj?.id?.toString() || '';

                        if (!userId) {
                            ElMessage.warning('用户信息不完整，请重新登录');
                        }
                        return userId;
                    } catch (error) {
                        // 处理 JSON 解析失败的异常（如格式错误）
                        console.error('解析用户信息失败：', error);
                        ElMessage.error('用户信息异常，请重新登录');
                        return '';
                    }
                };

                //当前登录用户Id
                const currentUserId = ref(getCurrentUserId());


                // -------------------------- 2. 原有基础方法（保留并补充） --------------------------
                // 加载仓库列表
                const getAllWIInfo = async () => {
                    try {
                        const res = await axios.get('/WhInbound/GetWareHouseInfoForSelect');
                        warehouseList.value = res.data && Array.isArray(res.data) ? res.data : [];
                    } catch (error) {
                        console.error('获取仓库列表失败：', error);
                        ElMessage.error('加载仓库数据失败，请重试');
                        warehouseList.value = [];
                    }
                };

                // 加载所有入库单
                const getAllInboundInfo = async () => {
                    try {
                        isLoading.value = true;
                        const res = await axios.get('/WhInbound/GetAllInfo');
                        tableData.value = res.data && Array.isArray(res.data) ? res.data : [];
                        total.value = tableData.value.length;
                    } catch (error) {
                        console.error('获取全部入库单失败：', error);
                        ElMessage.error('加载全部入库单失败，请重试');
                        tableData.value = [];
                        total.value = 0;
                    } finally {
                        isLoading.value = false;
                    }
                };

                const paginateFrontData = () => {
                    // 计算截取起始索引和结束索引
                    const startIndex = (currentPage.value - 1) * pageSize.value;
                    const endIndex = startIndex + pageSize.value;
                    // 从全量数据中截取当前页数据
                    tableData.value = allTableData.value.slice(startIndex, endIndex);
                };





                // 数据字典初始化
                const initDictData = () => {
                    try {
                        const stockInTypeStr = document.getElementById('app').dataset.stockInTypeList || '[]';
                        const orderStatusStr = document.getElementById('app').dataset.orderStatusList || '[]';
                        stockInTypeList.value = JSON.parse(stockInTypeStr) || [];
                        orderStatusList.value = JSON.parse(orderStatusStr) || [];
                    } catch (e) {
                        console.error('解析数据字典失败：', e);
                        ElMessage.error('数据字典加载异常');
                    }
                };

                // 状态文本格式化
                const getStatusText = (statusCode) => {
                    const code = Number(statusCode);
                    const matched = orderStatusList.value.find(item => Number(item.Code) === code);
                    return matched ? matched.Name : "未知状态";
                };

                // 入库类型格式化
                const getStockTypeText = (typeCode) => {
                    const code = Number(typeCode);
                    const matched = stockInTypeList.value.find(item => Number(item.Code) === code);
                    return matched ? matched.Name : "未知类型";
                };

                // 表格列格式化
                const formatStockTypeColumn = (row, column, cellValue) => getStockTypeText(cellValue);
                const formatOrderStatusColumn = (row, column, cellValue) => getStatusText(cellValue);
                const formatDate = (row, column, cellValue) => {
                    if (!cellValue) return '';
                    let date = new Date(cellValue instanceof Date ? cellValue : cellValue.replace(/T.*/, ''));
                    return date.getFullYear() === 1 ? '' : `${date.getFullYear()}-${String(date.getMonth()+1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
                };
                const formatAllGoodsName = (row, column, cellValue) => {
                    // 确保 cellValue 是字符串，兼容 null/undefined/对象等异常值
                    const value = String(cellValue || '');
                    if (value.length > 10) {
                        return value.slice(0, 10) + '...等';
                    }
                    return value;
                };

                // 查询方法
                const searchTable = async () => {
                    try {
                        isLoading.value = true;
                        const queryParams = {
                            StockOrderNo: orderNoInput.value || '',
                            StockType: selectedInboundType.value || '',
                            OrderStatus: selectedStatus.value || '',
                            WarehouseId: selectedWarehouse.value ? Number(selectedWarehouse.value) : 0,
                            StartTime: dateRange.value[0] ? new Date(dateRange.value[0]).toISOString() : '',
                            EndTime: dateRange.value[1] ? new Date(dateRange.value[1]).toISOString() : ''
                        };
                        const res = await axios.post('/WhInbound/GetSomeWhInboundInfo', queryParams, {
                            headers: { 'Content-Type': 'application/json' }
                        });
                        // 存储全量数据
                        allTableData.value = res.data && Array.isArray(res.data) ? res.data : [];
                        // 全量数据总数
                        total.value = allTableData.value.length;
                        // 执行前端分页，显示当前页数据
                        paginateFrontData();
                        if (tableData.value.length === 0) ElMessage.info('未查询到符合条件的入库单');
                    } catch (e) {
                        console.error('查询失败：', e);
                        ElMessage.error('查询失败，请检查网络或联系管理员');
                        allTableData.value = [];
                        tableData.value = [];
                        total.value = 0;
                    } finally {
                        isLoading.value = false;
                    }
                };

                // 重置表单
                const resetForm = () => {
                    orderNoInput.value = '';
                    selectedInboundType.value = '';
                    selectedStatus.value = '';
                    selectedWarehouse.value = '';
                    dateRange.value = [];
                    searchTable(); // 重置后自动查询全量数据
                };

                // 刷新方法
                const refrushTable = async () => {
                    try {
                        isLoading.value = true;
                        ElMessage.info('正在刷新数据...');
                        await getAllWIInfo();
                        // 重新加载全量数据
                        await searchTable();
                        // 清空选中状态（原有逻辑保留）
                        if (multipleTable.value) {
                            multipleTable.value.clearSelection();
                            selectedRows.value = [];
                        }
                        ElMessage.success('数据刷新成功！');
                    } catch (error) {
                        console.error('刷新失败：', error);
                        ElMessage.error('刷新失败，请稍后重试');
                    } finally {
                        isLoading.value = false;
                    }
                };

                // 分页方法
                const handleSizeChange = (val) => {
                    pageSize.value = val;
                    currentPage.value = 1; // 切换页大小时重置到第一页
                    paginateFrontData(); // 仅前端截取数据
                };

                // 当前页改变
                const handleCurrentChange = (val) => {
                    currentPage.value = val;
                    paginateFrontData(); // 仅前端截取数据
                    // 清空选中状态（原有逻辑保留）
                    if (multipleTable.value) {
                        multipleTable.value.clearSelection();
                        selectedRows.value = [];
                    }
                };


                // -------------------------- 3. 审核功能实现（核心逻辑） --------------------------
                const openAuditModal = () => {
                    if (selectedRows.value.length === 0) {
                        ElMessage.warning('请先选中需要审核的入库单！');
                        return;
                    }
                    // 筛选仅“待审核”状态的单据
                    canAuditRows.value = selectedRows.value.filter(row => Number(row.orderStatus) === 1);
                    if (canAuditRows.value.length === 0) {
                        ElMessage.error('选中的单据中无「待审核」状态的订单，请重新选择！');
                        return;
                    }
                    // 重置模态框数据
                    selectedAuditResult.value = '';
                    auditOpinion.value = '';
                    isAuditModalOpen.value = true;
                };

                // 3.2 关闭审核模态框
                const handleAuditModalClose = () => {
                    selectedAuditResult.value = '';
                    auditOpinion.value = '';
                    isAuditModalOpen.value = false;
                };

                // 3.3 确认批量审核
                const confirmAudit = async () => {
                    // 1. 基础校验
                    if (!selectedAuditResult.value) {
                        ElMessage.warning('请选择审核结果（通过/驳回）！');
                        return;
                    }
                    // 驳回时必须填写意见
                    if (selectedAuditResult.value === 'reject' && !auditOpinion.value.trim()) {
                        ElMessage.warning('驳回时必须填写审核意见！');
                        return;
                    }
                    // 校验登录人ID（审核人ID=登录人ID）
                    if (!currentUserId.value || Number(currentUserId.value) <= 0) {
                        ElMessage.error('未获取到有效登录人信息，请重新登录！');
                        return;
                    }

                    // 2. 构造控制器要求的参数格式（AuditeWhInbRequest）
                    const auditParams = {
                        WhOrderIdList: canAuditRows.value.map(row => Number(row.stockOrderId)),
                        OrderStatu: selectedAuditResult.value === 'pass' ? '3' : '2',
                        AuditorId: Number(currentUserId.value),
                        AuditorComment: auditOpinion.value.trim()
                    };

                    try {
                        isLoading.value = true;
                        // 3. 调用后端控制器接口
                        const res = await axios.post('/WhInbound/AuditeWhInboundOrder', auditParams, {
                            headers: { 'Content-Type': 'application/json' }
                        });

                        // 4. 处理响应
                        if (res.data >= 0) {
                            const successCount = res.data;
                            if (successCount > 0) {
                                ElMessage.success(`审核完成`);
                            } else {
                                ElMessage.info('未找到符合条件的单据，审核失败');
                                return;
                            }
                            // 5. 刷新数据+重置状态
                            handleAuditModalClose();
                            await getAllInboundInfo(); // 重新加载表格数据，更新状态显示
                            if (multipleTable.value) {
                                multipleTable.value.clearSelection(); // 清空表格选中状态
                                selectedRows.value = [];
                            }
                        } else {
                            ElMessage.error('审核失败：后端返回异常');
                        }
                    } catch (error) {
                        console.error('批量审核接口调用失败：', error);
                        ElMessage.error('审核请求发送失败，请检查网络或联系管理员');
                    } finally {
                        isLoading.value = false; // 无论成功失败，都关闭加载状态
                    }
                };


                // -------------------------- 4. 撤销功能实现（核心逻辑） --------------------------
                // 4.1 批量撤销（顶部按钮）
                const cancleCheck = async () => {
                    // 1. 基础校验：选中数据
                    if (selectedRows.value.length === 0) {
                        ElMessage.warning('请先选中需要撤销的入库单！');
                        return;
                    }

                    // 2. 筛选可撤销状态的单据（驳回=2、未入库=3，与审核状态逻辑对齐）
                    const canCancelRows = selectedRows.value.filter(row =>
                        [2].includes(Number(row.orderStatus))
                    );
                    if (canCancelRows.length === 0) {
                        ElMessage.error('选中的单据中无「驳回」态的订单，无法撤销！');
                        return;
                    }

                    // 3. 校验登录人ID（撤销人=登录人）
                    if (!currentUserId.value || Number(currentUserId.value) <= 0) {
                        ElMessage.error('未获取到有效登录人信息，请重新登录！');
                        return;
                    }

                    // 4. 确认撤销操作（提示状态变更结果）
                    ElMessageBox.confirm(
                        `确定要撤销 ${canCancelRows.length} 条单据吗？撤销后状态将恢复为「待审核」（状态值=1）`,
                        '确认撤销',
                        { type: 'warning', confirmButtonText: '确认撤销', cancelButtonText: '取消' }
                    ).then(async () => {
                        try {
                            isLoading.value = true;
                            // 5. 构造控制器要求的参数（ChangeWhInbStatuRequest）
                            const cancelParams = {
                                WhOrderIdList: canCancelRows.map(row => Number(row.stockOrderId)), // 订单ID列表（转long，匹配List<long>）
                                NewStatu: '1', // 撤销后目标状态：待审核=1（转字符串，匹配控制器string类型）
                                UserId: Number(currentUserId.value) // 撤销人ID=登录人ID（转long，匹配控制器long类型）
                            };

                            // 6. 调用后端撤销控制器接口（地址与 [HttpPost("ChangeWhInboundStatu")] 完全匹配）
                            const res = await axios.post('/WhInbound/ChangeWhInboundStatu', cancelParams, {
                                headers: { 'Content-Type': 'application/json' }
                            });

                            // 7. 处理响应（控制器返回受影响行数 int）
                            if (res.data >= 0) {
                                const successCount = res.data;
                                if (successCount > 0) {
                                    ElMessage.success(`批量撤销成功！共处理 ${successCount} 条单据，状态已恢复为「待审核」`);
                                } else {
                                    ElMessage.info('未找到符合条件的单据，撤销失败');
                                    return;
                                }
                                // 8. 刷新数据+重置状态
                                await getAllInboundInfo(); // 重新加载表格，更新状态显示
                                if (multipleTable.value) {
                                    multipleTable.value.clearSelection(); // 清空选中行
                                    selectedRows.value = [];
                                }
                            } else {
                                ElMessage.error('撤销失败：后端返回异常');
                            }
                        } catch (error) {
                            console.error('批量撤销接口调用失败：', error);
                            ElMessage.error('撤销请求发送失败，请检查网络或联系管理员');
                        } finally {
                            isLoading.value = false; // 关闭加载状态
                        }
                    }).catch(() => {
                        ElMessage.info('已取消撤销操作');
                    });
                };

                // 4.2 单行撤销（操作列按钮）
                const handleRejectCancel = async (row) => {
                    // 1. 校验当前单据状态
                    if (![2].includes(Number(row.orderStatus))) {
                        ElMessage.error(`当前「${getStatusText(row.orderStatus)}」状态不可撤销！`);
                        return;
                    }

                    // 2. 校验登录人ID
                    if (!currentUserId.value || Number(currentUserId.value) <= 0) {
                        ElMessage.error('未获取到有效登录人信息，请重新登录！');
                        return;
                    }

                    // 3. 确认撤销操作
                    ElMessageBox.confirm(
                        `确定要撤销单据【${row.stockOrderNo || row.stockOrderId}】吗？撤销后状态将恢复为「待审核」（状态值=1）`,
                        '确认撤销',
                        { type: 'warning', confirmButtonText: '确认撤销', cancelButtonText: '取消' }
                    ).then(async () => {
                        try {
                            isLoading.value = true;
                            // 4. 构造参数（WhOrderIdList 传数组，适配控制器批量参数格式）
                            const cancelParams = {
                                WhOrderIdList: [Number(row.stockOrderId)], // 单条ID转数组
                                NewStatu: '1', // 目标状态：待审核=1
                                UserId: Number(currentUserId.value) // 撤销人=登录人
                            };

                            // 5. 调用与批量撤销相同的控制器接口
                            const res = await axios.post('/WhInbound/ChangeWhInboundStatu', cancelParams, {
                                headers: { 'Content-Type': 'application/json' }
                            });

                            // 6. 处理响应
                            if (res.data > 0) {
                                ElMessage.success(`单据【${row.stockOrderNo || row.stockOrderId}】撤销成功！状态已恢复为「待审核」`);
                                await getAllInboundInfo(); // 刷新表格数据
                            } else if (res.data === 0) {
                                ElMessage.info('该单据已被处理或不存在，撤销失败');
                            } else {
                                ElMessage.error('撤销失败：后端返回异常');
                            }
                        } catch (error) {
                            console.error(`单条撤销失败（ID: ${row.stockOrderId}）：`, error);
                            ElMessage.error('撤销请求发送失败，请检查网络');
                        } finally {
                            isLoading.value = false;
                        }
                    }).catch(() => {
                        ElMessage.info('已取消撤销操作');
                    });
                };


                // -------------------------- 5. 删除功能实现（核心逻辑） --------------------------
                // 5.1 批量删除（顶部按钮，适配 DeleteWhInbRequest 参数）
                const deleteOrder = async () => {
                    // 1. 校验选中数据
                    if (selectedRows.value.length === 0) {
                        ElMessage.warning('请先选中需要删除的入库单！');
                        return;
                    }

                    // 2. 筛选可删除状态的单据（仅草稿=0、待审核=1 可删）
                    const canDeleteRows = selectedRows.value.filter(row =>
                        [0, 1].includes(Number(row.orderStatus))
                    );
                    if (canDeleteRows.length === 0) {
                        ElMessage.error('仅「草稿」或「待审核」状态的单据可删除，请重新选择！');
                        return;
                    }

                    // 3. 校验登录人ID（从 sessionStorage 获取的 currentUserId）
                    if (!currentUserId.value || Number(currentUserId.value) <= 0) {
                        ElMessage.error('未获取到有效登录人信息，请重新登录！');
                        return;
                    }

                    // 4. 确认删除操作（危险操作提示）
                    ElMessageBox.confirm(
                        `确定要删除 ${canDeleteRows.length} 条单据吗？删除后不可恢复！`,
                        '警告',
                        { type: 'error', confirmButtonText: '确认删除', cancelButtonText: '取消' }
                    ).then(async () => {
                        try {
                            isLoading.value = true;
                            // 5. 构造控制器要求的参数格式：DeleteWhInbRequest（含 OrderIdList 和 UserId）
                            const deleteParams = {
                                OrderIdList: canDeleteRows.map(row => Number(row.stockOrderId)), // 订单ID列表（转数字，匹配long类型）
                                UserId: Number(currentUserId.value) // 登录人ID（转数字，匹配long类型）
                            };

                            // 6. 调用后端控制器接口（地址与控制器 [HttpPost("DeleteWhInbound")] 匹配）
                            const res = await axios.post('/WhInbound/DeleteWhInbound', deleteParams, {
                                headers: { 'Content-Type': 'application/json' }
                            });

                            // 7. 处理响应（控制器返回受影响行数 int）
                            if (res.data >= 0) {
                                // 后端返回受影响行数，判断是否删除成功（res.data > 0 表示有数据被删除）
                                const successCount = res.data;
                                if (successCount > 0) {
                                    ElMessage.success(`删除成功！共删除 ${successCount} 条单据`);
                                } else {
                                    ElMessage.info('未找到符合条件的单据，删除失败');
                                }
                                // 8. 刷新数据+清空选中状态
                                await getAllInboundInfo();
                                if (multipleTable.value) {
                                    multipleTable.value.clearSelection();
                                    selectedRows.value = [];
                                }
                            } else {
                                ElMessage.error('删除失败：后端返回异常');
                            }
                        } catch (error) {
                            console.error('批量删除接口调用失败：', error);
                            ElMessage.error('删除请求发送失败，请检查网络或联系管理员');
                        } finally {
                            isLoading.value = false;
                        }
                    }).catch(() => {
                        ElMessage.info('已取消删除操作');
                    });
                };

                // 5.2 单行删除（操作列按钮，同样适配控制器参数）
                const deleteSingleOrder = async (row) => {
                    // 1. 校验当前单据状态（仅草稿=0、待审核=1 可删）
                    if (![0, 1].includes(Number(row.orderStatus))) {
                        ElMessage.error(`当前「${getStatusText(row.orderStatus)}」状态不可删除！`);
                        return;
                    }

                    // 2. 校验登录人ID
                    if (!currentUserId.value || Number(currentUserId.value) <= 0) {
                        ElMessage.error('未获取到有效登录人信息，请重新登录！');
                        return;
                    }

                    // 3. 确认删除操作
                    ElMessageBox.confirm(
                        `确定要删除单据【${row.stockOrderNo || row.stockOrderId}】吗？删除后不可恢复！`,
                        '警告',
                        { type: 'error', confirmButtonText: '确认删除', cancelButtonText: '取消' }
                    ).then(async () => {
                        try {
                            isLoading.value = true;
                            // 4. 构造参数（OrderIdList 传数组，即使单条也符合控制器要求）
                            const deleteParams = {
                                OrderIdList: [Number(row.stockOrderId)], // 单条订单ID转数组
                                UserId: Number(currentUserId.value) // 登录人ID（转数字）
                            };

                            // 5. 调用同一个后端控制器接口
                            const res = await axios.post('/WhInbound/DeleteWhInbound', deleteParams, {
                                headers: { 'Content-Type': 'application/json' }
                            });

                            // 6. 处理响应
                            if (res.data > 0) {
                                ElMessage.success(`单据【${row.stockOrderNo || row.stockOrderId}】删除成功！`);
                                await getAllInboundInfo(); // 刷新数据
                            } else if (res.data === 0) {
                                ElMessage.info('未找到该单据或单据已被删除');
                            } else {
                                ElMessage.error('删除失败：后端返回异常');
                            }
                        } catch (error) {
                            console.error(`单行删除失败（ID: ${row.stockOrderId}）：`, error);
                            ElMessage.error('删除请求发送失败，请检查网络或联系管理员');
                        } finally {
                            isLoading.value = false;
                        }
                    }).catch(() => {
                        ElMessage.info('已取消删除操作');
                    });
                };


                // -------------------------- 6. 其他占位方法（根据实际需求补充） --------------------------
                // 新增订单（跳转页面示例）
                const addOrder = () => {
                    window.location.href = '/WhInbound/AddIndex'; // 跳转新增页面
                };

                // 复制订单（示例逻辑）
                const copyOrder = () => {
                    if (selectedRows.value.length === 0) {
                        ElMessage.warning('请先选中需要复制的入库单！');
                        return;
                    }
                    if (selectedRows.value.length > 1) {
                        ElMessage.warning('仅支持单条单据复制，请重新选择！');
                        return;
                    }
                    const targetRow = selectedRows.value[0];
                    // 跳转复制页面并携带原单据ID
                    window.location.href = `/WhInbound/CopyIndex?orderId=${targetRow.stockOrderId}`;
                };

                // 导出订单（示例逻辑）
                const exportTable = async () => {
                    try {
                        // 构造导出参数（与查询参数一致）
                        const exportParams = {
                            StockOrderNo: orderNoInput.value || '',
                            StockType: selectedInboundType.value || '',
                            OrderStatus: selectedStatus.value || '',
                            WarehouseId: selectedWarehouse.value ? Number(selectedWarehouse.value) : 0,
                            StartTime: dateRange.value[0] ? new Date(dateRange.value[0]).toISOString() : '',
                            EndTime: dateRange.value[1] ? new Date(dateRange.value[1]).toISOString() : ''
                        };

                        // 生成导出URL（后端接口返回文件流）
                        const exportUrl = `/WhInbound/ExportInboundOrder?` +
                            Object.entries(exportParams).map(([key, val]) => `${key}=${encodeURIComponent(val)}`).join('&');

                        // 创建a标签触发下载
                        const link = document.createElement('a');
                        link.href = exportUrl;
                        link.download = `入库单列表_${new Date().toLocaleDateString()}.xlsx`;
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);

                        ElMessage.success('导出请求已发送，正在下载...');
                    } catch (error) {
                        console.error('导出失败：', error);
                        ElMessage.error('导出请求发送失败，请检查网络');
                    }
                };

                // 编辑订单（跳转页面示例）
                const handleEdit = (row) => {
                    window.location.href = `/WhInbound/EditIndex?orderId=${row.stockOrderId}`; // 跳转编辑页面
                };

                // 查看详情（跳转页面示例）
                const jumpToDetail = (row) => {
                    window.location.href = `/WhInbound/DetailIndex?orderId=${row.stockOrderId}`; // 跳转详情页面
                };

                // 表格选中行变化
                const handleSelectionChange = (val) => {
                    selectedRows.value = val;
                };


                // -------------------------- 7. 页面初始化 --------------------------
                onMounted(async () => {
                    initDictData(); // 初始化数据字典
                    try {
                        await getAllWIInfo(); // 加载仓库列表
                        await searchTable(); // 初始查询数据
                    } catch (error) {
                        console.error('页面初始化失败：', error);
                        ElMessage.error('页面加载失败，请刷新重试');
                    }
                });


                // -------------------------- 8. 暴露变量与方法到模板 --------------------------
                return {
                    // 基础数据
                    stockInTypeList,
                    orderStatusList,
                    warehouseList,
                    tableData,
                    currentPage,
                    pageSize,
                    total,
                    isLoading,
                    // 查询条件
                    orderNoInput,
                    selectedInboundType,
                    selectedStatus,
                    selectedWarehouse,
                    dateRange,
                    // 表格与模态框
                    multipleTable,
                    selectedRows,
                    isAuditModalOpen,
                    selectedAuditResult,
                    auditOpinion,
                    // 格式化方法
                    formatStockTypeColumn,
                    formatOrderStatusColumn,
                    formatDate,
                    formatAllGoodsName,
                    getStatusText,
                    // 核心方法
                    searchTable,
                    resetForm,
                    refrushTable,
                    handleSizeChange,
                    handleCurrentChange,
                    openAuditModal,
                    handleAuditModalClose,
                    confirmAudit,
                    cancleCheck,
                    handleRejectCancel,
                    deleteOrder,
                    deleteSingleOrder,
                    addOrder,
                    copyOrder,
                    exportTable,
                    handleEdit,
                    jumpToDetail,
                    handleSelectionChange
                };
            }
        });
        app.use(ElementPlus, {
            locale: ElementPlusLocaleZhCn
        });
        app.mount('#app');
    </script>
</body>
</html>